﻿namespace Leetcode.N0032;
public class Solution
{
    public int LongestValidParentheses(string s)
    {
        var stack = new System.Collections.Generic.Stack<(int Index, int Length)>();
        var maxLength = 0;
        var curLength = 0;
        for (var i = 0; i < s.Length; i++)
        {
            if (s[i] == '(')
            {
                stack.Push((i, curLength));
                curLength = 0;
            }
            else if (stack.Count == 0)
            {
                curLength = 0;
            }
            else if (stack.Count > 0)
            {
                var p = stack.Pop();
                curLength = i - p.Index + 1 + p.Length;
                maxLength = Math.Max(maxLength, curLength);
            }

        }
        return maxLength;
    }
}
